package com.ffcs.crmd.tsp.server.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PingHelper {
    
    //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
    private static int getCheckResult(String line) {
        Pattern pattern = Pattern.compile("TTL=\\d+", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
    
    public static void ping(String ipAddress) throws Exception {
        String line = null;
        try {
            Process pro = Runtime.getRuntime().exec("ping " + ipAddress);
            BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            while ((line = buf.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    public static boolean ping(String ipAddress, int timeout) throws Exception {
        boolean status = InetAddress.getByName(ipAddress).isReachable(timeout);
        return status;
    }
    
    public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.redirectErrorStream(true);
            if (OSinfo.isWindows()) {
                processBuilder.command(
                    new String[] {"cmd", "/c", "ping " + ipAddress + " -n " + String.valueOf(pingTimes) + " -w " + String.valueOf(timeOut * 1000) });
            } else {
                processBuilder.command(
                    new String[] {"/bin/sh", "-c", "ping " + ipAddress + " -c " + String.valueOf(pingTimes) + " -W " + String.valueOf(timeOut)});
            }
            
            Process process = processBuilder.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            int connectedCount = 0;
            String line = null;
            while ((line = br.readLine()) != null) {
                connectedCount += getCheckResult(line);
            }
            br.close();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                return connectedCount == pingTimes;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }
    
    public static void main(String[] args) {
        System.out.println(PingHelper.ping("192.168.55.246", 3, 5));
    }
}
